package services

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"encoding/base64"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	baseModels "gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// OpenCard 单卡开卡
func OpenCard(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	// 解析请求体以获取用户ID和昵称
	var requestBody struct {
		UserID               int64  `json:"userId"`
		Nickname             string `json:"nickname"`
		AccountId            string `json:"accountId"`
		CardBin              string `json:"cardBin"`
		CardholderId         string `json:"cardholderId"`
		CardCurrency         string `json:"cardCurrency"`
		CardExpirationDate   int    `json:"cardExpirationDate"`
		CardScheme           string `json:"cardScheme"`
		CardType             string `json:"cardType"`
		CardFormFactor       string `json:"cardFormFactor"`
		RechargeAmount       string `json:"rechargeAmount,omitempty"`
		RequestId            string `json:"requestId"`
		TransactionLimitType string `json:"transactionLimitType"`
	}
	if err := json.Unmarshal(bodyBytes, &requestBody); err != nil {
		return nil, fmt.Errorf("failed to parse request body: %v", err)
	}

	// 验证用户是否存在
	var user baseModels.User
	if err := database.DB.First(&user, requestBody.UserID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("user not found: %d", requestBody.UserID)
		}
		return nil, fmt.Errorf("failed to check user: %v", err)
	}

	// 发送开卡请求
	path := "/vcc/openApi/v4/openCard"
	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	if err != nil {
		return nil, fmt.Errorf("open card failed: %v", err)
	}

	// 打印原始响应用于调试
	fmt.Printf("原始响应: %s\n", string(resp))
	fmt.Printf("响应字节: %v\n", resp)

	// 尝试base64解码响应
	var decodedResp []byte
	if len(resp) > 0 {
		// 检查响应是否是base64编码的
		decodedResp, err = base64.StdEncoding.DecodeString(string(resp))
		if err != nil {
			// 如果不是base64编码，直接使用原始响应
			decodedResp = resp
			fmt.Printf("使用原始响应（非base64编码）\n")
		} else {
			fmt.Printf("使用base64解码后的响应\n")
		}
	} else {
		decodedResp = resp
		fmt.Printf("响应为空\n")
	}

	// 解析响应
	var response models.OpenCardResponse
	if err := json.Unmarshal(decodedResp, &response); err != nil {
		fmt.Printf("JSON解析失败: %v\n", err)
		fmt.Printf("尝试解析的数据: %s\n", string(decodedResp))

		// 尝试解析为通用错误响应
		var errorResponse map[string]interface{}
		if err2 := json.Unmarshal(decodedResp, &errorResponse); err2 != nil {
			// 如果连错误响应都解析不了，返回通用错误
			standardErrorResponse := struct {
				Code string `json:"code"`
				Msg  struct {
					CN string `json:"CN"`
					EN string `json:"EN"`
					VN string `json:"VN"`
				} `json:"msg"`
				Data string `json:"data"`
			}{
				Code: "400",
				Msg: struct {
					CN string `json:"CN"`
					EN string `json:"EN"`
					VN string `json:"VN"`
				}{
					CN: "开卡失败",
					EN: "Failed to open card",
					VN: "Mở thẻ thất bại",
				},
				Data: "响应解析失败",
			}

			errorBytes, _ := json.Marshal(standardErrorResponse)
			return errorBytes, nil
		}

		// 如果是错误响应，构造标准错误响应
		if _, ok := errorResponse["code"].(string); ok {
			if msg, ok := errorResponse["msg"].(string); ok {
				// 构造标准错误响应
				standardErrorResponse := struct {
					Code string `json:"code"`
					Msg  struct {
						CN string `json:"CN"`
						EN string `json:"EN"`
						VN string `json:"VN"`
					} `json:"msg"`
					Data string `json:"data"`
				}{
					Code: "400",
					Msg: struct {
						CN string `json:"CN"`
						EN string `json:"EN"`
						VN string `json:"VN"`
					}{
						CN: "开卡失败",
						EN: "Failed to open card",
						VN: "Mở thẻ thất bại",
					},
					Data: msg,
				}

				errorBytes, _ := json.Marshal(standardErrorResponse)
				return errorBytes, nil
			}
		}

		// 如果无法解析，返回通用错误
		standardErrorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data string `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "开卡失败",
				EN: "Failed to open card",
				VN: "Mở thẻ thất bại",
			},
			Data: "响应格式错误",
		}

		errorBytes, _ := json.Marshal(standardErrorResponse)
		return errorBytes, nil
	}

	// 如果开卡成功，保存卡信息到数据库并更新昵称
	if response.Code == "0000" && response.Data.CardDetail.CardId != "" {
		// 创建卡记录，只包含数据库表中存在的字段
		card := baseModels.UserCard{
			UserID:              requestBody.UserID,
			CardID:              response.Data.CardDetail.CardId,
			Platform:            "photonpay",
			CardStatus:          mapCardStatus(response.Data.CardDetail.CardStatus),
			NikeName:            requestBody.Nickname,
			CardBin:             response.Data.CardDetail.CardNo[:6], // 取卡号前6位作为BIN号
			TotalTransferAmount: decimal.NewFromInt(0),               // 使用 decimal 初始化总转账金额为0
			CardType:            requestBody.CardType,                // 设置卡类型
		}

		// 开始事务
		tx := database.DB.Begin()
		if tx.Error != nil {
			return nil, fmt.Errorf("start transaction failed: %v", tx.Error)
		}

		// 保存到数据库
		if err := tx.Create(&card).Error; err != nil {
			tx.Rollback()
			log.Printf("Failed to save card info: %v", err)
			return nil, fmt.Errorf("save card info failed: %v", err)
		}

		// 如果有充值金额，处理充值逻辑
		if requestBody.RechargeAmount != "" {
			rechargeAmount, err := decimal.NewFromString(requestBody.RechargeAmount)
			if err != nil {
				tx.Rollback()
				return nil, fmt.Errorf("invalid recharge amount format: %v", err)
			}

			// 更新卡片的 TotalTransferAmount
			if err := tx.Model(&baseModels.UserCard{}).
				Where("card_id = ?", response.Data.CardDetail.CardId).
				Update("TotalTransferAmount", rechargeAmount).Error; err != nil {
				tx.Rollback()
				return nil, fmt.Errorf("update card amount failed: %v", err)
			}

			// 根据用户角色扣减余额
			var roleID int64
			var userRole baseModels.UserRole
			if err := tx.Where("user_id = ?", requestBody.UserID).First(&userRole).Error; err == nil {
				roleID = userRole.RoleID
			} else {
				tx.Rollback()
				return nil, fmt.Errorf("failed to get user role: %v", err)
			}

			switch roleID {
			case 2: // 普通用户，不需要处理主子账户扣款
				// 直接跳过扣款逻辑
				log.Printf("PhotonPay开卡 - 普通用户跳过余额扣除: UserID=%d, 金额=%s", requestBody.UserID, rechargeAmount.String())
			case 3: // 主账号
				// 先检查余额是否足够
				var masterAccount baseModels.MasterAccount
				if err := tx.Where("user_id = ?", requestBody.UserID).First(&masterAccount).Error; err != nil {
					tx.Rollback()
					return nil, fmt.Errorf("failed to get master account: %v", err)
				}

				if masterAccount.Balance.LessThan(rechargeAmount) {
					tx.Rollback()
					return nil, fmt.Errorf("insufficient master account balance: %s < %s", masterAccount.Balance.String(), rechargeAmount.String())
				}

				if err := tx.Model(&baseModels.MasterAccount{}).
					Where("user_id = ?", requestBody.UserID).
					Update("balance", gorm.Expr("balance - ?", rechargeAmount)).Error; err != nil {
					tx.Rollback()
					return nil, fmt.Errorf("failed to deduct master account balance: %v", err)
				}

				log.Printf("PhotonPay开卡 - 主账号余额扣除成功: UserID=%d, 扣除金额=%s, 剩余余额=%s",
					requestBody.UserID, rechargeAmount.String(), masterAccount.Balance.Sub(rechargeAmount).String())
			case 5: // 子账号
				// 先检查余额是否足够
				var subAccount baseModels.SubAccount
				if err := tx.Where("user_id = ?", requestBody.UserID).First(&subAccount).Error; err != nil {
					tx.Rollback()
					return nil, fmt.Errorf("failed to get sub account: %v", err)
				}

				if subAccount.Balance.LessThan(rechargeAmount) {
					tx.Rollback()
					return nil, fmt.Errorf("insufficient sub account balance: %s < %s", subAccount.Balance.String(), rechargeAmount.String())
				}

				if err := tx.Model(&baseModels.SubAccount{}).
					Where("user_id = ?", requestBody.UserID).
					Update("balance", gorm.Expr("balance - ?", rechargeAmount)).Error; err != nil {
					tx.Rollback()
					return nil, fmt.Errorf("failed to deduct sub account balance: %v", err)
				}

				log.Printf("PhotonPay开卡 - 子账号余额扣除成功: UserID=%d, 扣除金额=%s, 剩余余额=%s",
					requestBody.UserID, rechargeAmount.String(), subAccount.Balance.Sub(rechargeAmount).String())
			default:
				tx.Rollback()
				return nil, fmt.Errorf("invalid user role: %d", roleID)
			}
		}

		// 提交事务
		if err := tx.Commit().Error; err != nil {
			return nil, fmt.Errorf("commit transaction failed: %v", err)
		}

		// 如果有昵称，更新卡片配置
		if requestBody.Nickname != "" {
			updateBody := map[string]interface{}{
				"cardId":    response.Data.CardDetail.CardId,
				"requestId": fmt.Sprintf("UPDATE_%s", requestBody.RequestId),
				"nickname":  requestBody.Nickname,
			}
			updateBytes, err := json.Marshal(updateBody)
			if err != nil {
				log.Printf("Failed to marshal update request: %v", err)
			} else {
				_, err = UpdateCard(ctx, client, updateBytes)
				if err != nil {
					log.Printf("Failed to update card nickname: %v", err)
				}
			}
		}

		// 构造标准成功响应
		standardResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data map[string]interface{} `json:"data"`
		}{
			Code: "200",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "开卡成功",
				EN: "Card opened successfully",
				VN: "Mở thẻ thành công",
			},
			Data: map[string]interface{}{
				"cardBin":      response.Data.CardDetail.CardNo[:6],
				"cardCurrency": response.Data.CardDetail.CardCurrency,
				"cardId":       response.Data.CardDetail.CardId,
				"cardNo":       response.Data.CardDetail.CardNo,
				"cardScheme":   response.Data.CardDetail.CardScheme,
				"cardStatus":   response.Data.CardDetail.CardStatus,
				"cardType":     response.Data.CardDetail.CardType,
			},
		}

		// 返回标准响应
		return json.Marshal(standardResponse)
	}

	// 如果开卡失败，返回错误响应
	errorResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data string `json:"data"`
	}{
		Code: "400",
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "开卡失败",
			EN: "Failed to open card",
			VN: "Mở thẻ thất bại",
		},
		Data: response.Msg,
	}

	return json.Marshal(errorResponse)
}

// mapCardStatus 将平台卡状态映射到系统卡状态
func mapCardStatus(platformStatus string) string {
	switch platformStatus {
	case "active":
		return "active"
	case "inactive":
		return "inactive"
	case "frozen":
		return "frozen"
	case "closed":
		return "closed"
	case "normal":
		return "normal" // 将 normal 状态映射为 active
	default:
		return "inactive"
	}
}

// UpdateCard 更新卡配置，bodyBytes 用于签名和请求体
func UpdateCard(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/vcc/openApi/v4/updateCard"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("参数", ctx, path, string(bodyBytes))
	if err != nil {
		return nil, fmt.Errorf("update card failed: %v", err)
	}

	var result models.OpenCardResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		// 构造错误响应
		errorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data string `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "更新卡片失败",
				EN: "Failed to update card",
				VN: "Cập nhật thẻ thất bại",
			},
			Data: result.Msg,
		}

		return json.Marshal(errorResponse)
	}

	// 构造成功响应
	successResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data map[string]interface{} `json:"data"`
	}{
		Code: "200",
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "更新卡片成功",
			EN: "Card updated successfully",
			VN: "Cập nhật thẻ thành công",
		},
		Data: map[string]interface{}{
			"message": "操作成功",
		},
	}

	return json.Marshal(successResponse)
}

// FreezeCard 冻结/解冻卡片，bodyBytes 用于签名和请求体
func FreezeCard(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/vcc/openApi/v4/freezeCard"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("参数", ctx, path, string(bodyBytes))
	if err != nil {
		return nil, fmt.Errorf("freeze card failed: %v", err)
	}

	// 打印原始响应用于调试
	fmt.Printf("[FreezeCard] 原始响应: %s\n", string(resp))

	// 解析响应
	var response struct {
		Code string          `json:"code"`
		Msg  string          `json:"msg"`
		Data json.RawMessage `json:"data"`
	}
	if err := json.Unmarshal(resp, &response); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	fmt.Printf("[FreezeCard] 解析后的响应: Code=%s, Msg=%s\n", response.Code, response.Msg)

	// 检查响应状态 - PhotonPay成功时返回"0000"，失败时返回其他值
	if response.Code != "0000" {
		// 构造错误响应
		errorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data string `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "冻结/解冻卡片失败",
				EN: "Failed to freeze/unfreeze card",
				VN: "Đóng băng/mở khóa thẻ thất bại",
			},
			Data: response.Msg,
		}

		return json.Marshal(errorResponse)
	}

	// 构造成功响应
	standardResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data map[string]interface{} `json:"data"`
	}{
		Code: "0000", // 使用"0000"而不是"200"以保持一致性
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "冻结/解冻卡片成功",
			EN: "Card freeze/unfreeze successful",
			VN: "Đóng băng/mở khóa thẻ thành công",
		},
		Data: map[string]interface{}{
			"message": "操作成功",
		},
	}

	return json.Marshal(standardResponse)
}

// CancelCard 销卡，bodyBytes 用于签名和请求体
func CancelCard(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/vcc/openApi/v4/cancelCard"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("参数", ctx, path, string(bodyBytes))
	if err != nil {
		return nil, fmt.Errorf("cancel card failed: %v", err)
	}

	var result models.OpenCardResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		// 构造错误响应
		errorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data string `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "销卡失败",
				EN: "Failed to cancel card",
				VN: "Hủy thẻ thất bại",
			},
			Data: result.Msg,
		}

		return json.Marshal(errorResponse)
	}

	// 构造成功响应
	successResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data map[string]interface{} `json:"data"`
	}{
		Code: "200",
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "销卡成功",
			EN: "Card cancelled successfully",
			VN: "Hủy thẻ thành công",
		},
		Data: map[string]interface{}{
			"message": "操作成功",
		},
	}

	return json.Marshal(successResponse)
}

// RechargeReturn 卡金额退还，bodyBytes 用于签名和请求体
func RechargeReturn(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	// 调用远程接口
	path := "/vcc/openApi/v4/rechargeReturn"
	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("返回", resp)
	if err != nil {
		return nil, fmt.Errorf("recharge return failed: %v", err)
	}

	var result models.OpenCardResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		// 构造错误响应
		errorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data string `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "金额退还失败",
				EN: "Failed to return amount",
				VN: "Hoàn tiền thất bại",
			},
			Data: result.Msg,
		}

		return json.Marshal(errorResponse)
	}

	// 构造成功响应
	successResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data map[string]interface{} `json:"data"`
	}{
		Code: "200",
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "金额退还成功",
			EN: "Amount returned successfully",
			VN: "Hoàn tiền thành công",
		},
		Data: map[string]interface{}{
			"message": "操作成功",
		},
	}

	return json.Marshal(successResponse)
}

// SimulateTransaction 模拟交易
func SimulateTransaction(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	// 解析请求体
	var requestBody struct {
		RequestID           string  `json:"requestId"`
		CardID              string  `json:"cardID"`
		CVV                 string  `json:"cvv"`
		ExpirationDate      string  `json:"expirationDate"`
		OriginTransactionID string  `json:"originTransactionId"`
		TxnCurrency         string  `json:"txnCurrency"`
		TxnAmount           float64 `json:"txnAmount"`
		TxnType             string  `json:"txnType"`
		MCC                 string  `json:"mcc"`
		MerchantName        string  `json:"merchantName"`
		MerchantCountry     string  `json:"merchantCountry"`
		MerchantCity        string  `json:"merchantCity"`
		MerchantPostcode    string  `json:"merchantPostcode"`
	}

	if err := json.Unmarshal(bodyBytes, &requestBody); err != nil {
		return nil, fmt.Errorf("failed to parse request body: %v", err)
	}

	// 验证必填字段
	if requestBody.RequestID == "" || requestBody.CardID == "" || requestBody.CVV == "" ||
		requestBody.ExpirationDate == "" || requestBody.TxnCurrency == "" || requestBody.TxnType == "" ||
		requestBody.MCC == "" || requestBody.MerchantName == "" || requestBody.MerchantCountry == "" ||
		requestBody.MerchantCity == "" || requestBody.MerchantPostcode == "" {
		return nil, fmt.Errorf("missing required fields")
	}

	// 验证交易类型
	if requestBody.TxnType != "auth" && requestBody.TxnType != "void" && requestBody.TxnType != "refund" {
		return nil, fmt.Errorf("invalid transaction type: %s", requestBody.TxnType)
	}

	// 如果是 void 或 refund 类型，需要验证 originTransactionId
	if (requestBody.TxnType == "void" || requestBody.TxnType == "refund") && requestBody.OriginTransactionID == "" {
		return nil, fmt.Errorf("originTransactionId is required for %s transaction", requestBody.TxnType)
	}

	// 发送请求到沙箱环境
	path := "/vcc/open/v2/sandBoxTransaction"
	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	if err != nil {
		return nil, fmt.Errorf("simulate transaction failed: %v", err)
	}

	// 解析响应
	var response struct {
		Code string `json:"code"`
		Msg  string `json:"msg"`
	}

	if err := json.Unmarshal(resp, &response); err != nil {
		return nil, fmt.Errorf("failed to parse response: %v", err)
	}

	// 构造标准响应
	standardResponse := struct {
		Code string `json:"code"`
		Msg  struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		} `json:"msg"`
		Data map[string]interface{} `json:"data"`
	}{
		Code: "200",
		Msg: struct {
			CN string `json:"CN"`
			EN string `json:"EN"`
			VN string `json:"VN"`
		}{
			CN: "交易模拟成功",
			EN: "Transaction simulation successful",
			VN: "Mô phỏng giao dịch thành công",
		},
		Data: map[string]interface{}{
			"requestId": requestBody.RequestID,
			"cardId":    requestBody.CardID,
			"txnType":   requestBody.TxnType,
			"amount":    requestBody.TxnAmount,
			"currency":  requestBody.TxnCurrency,
		},
	}

	// 如果原始响应不是成功状态，返回错误响应
	if response.Code != "0000" {
		errorResponse := struct {
			Code string `json:"code"`
			Msg  struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			} `json:"msg"`
			Data string `json:"data"`
		}{
			Code: "400",
			Msg: struct {
				CN string `json:"CN"`
				EN string `json:"EN"`
				VN string `json:"VN"`
			}{
				CN: "交易模拟失败",
				EN: "Transaction simulation failed",
				VN: "Mô phỏng giao dịch thất bại",
			},
			Data: response.Msg,
		}

		return json.Marshal(errorResponse)
	}

	return json.Marshal(standardResponse)
}
